package pers.qianyu.diytomcat.classloader;

import cn.hutool.core.util.*;
import pers.qianyu.diytomcat.catalina.*;
import pers.qianyu.diytomcat.constants.*;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;

/**
 * @author mizzle rain
 * @date 2021-01-13 16:03
 */
public class JspClassLoader extends URLClassLoader {
    private static Map<String, JspClassLoader> map = new ConcurrentHashMap<>();

    public static void invalidJspClassLoader(String uri, Context context) {
        String key = context.getPath() + "/" + uri;
        map.remove(key);
    }

    public static JspClassLoader getJspClassLoader(String uri, Context context) {
        String key = context.getPath() + "/" + uri;
        JspClassLoader jspClassLoader = map.get(key);
        if (Objects.isNull(jspClassLoader)) {
            jspClassLoader = new JspClassLoader(context);
            map.put(key, jspClassLoader);
        }
        return jspClassLoader;
    }

    public JspClassLoader(Context context) {
        super(new URL[]{}, context.getWebappClassLoader());
        try {
            String path = context.getPath();
            String subFolder = Objects.equals(path, "/") ? "_"
                    : StrUtil.subAfter(path, "/", false);
            File file = new File(Locations.WORK_FOLDER_PATH, subFolder);
            URL url = new URL("file:" + file.getAbsolutePath() + "/");
            addURL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}
